import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import Code from "@/utils/code";
import { getToken,setToken } from '@/utils/auth'
import router from "@/router";


// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
  headers:{
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 0, it is judged as an error.
    if (res.code) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === Code.LOGIN_TIMOUT||res.code === Code.REFRESH_FAILD) {
        // to re-login
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            window.location.href='http://'+ window.location.host
          })
        })
      }else if(res.code===Code.TOKEN_TIMEOUT){
        //刷新token重新请求接口
        const config = response.config
        if (!isRefreshing){
          isRefreshing=true
          const token = getToken()
          return service.request({
                    method:'get',
                    url:'/auth/refresh',
                    params:{token}
                  }).then(resp=>{
                    const access_token = resp.data.token
                    setToken(access_token)
                    requests.forEach(cb=>cb(access_token))
                    requests=[]
                    return service(config)
                  }).catch(err=>{
                    console.error('refreshtoken err=>',err)
                  }).finally(()=>{
                    isRefreshing=false
                  })
        }else {
          return new Promise((resolve)=>{
            requests.push((token)=>{
              config.headers['Authorization'] = 'Bearer ' + token
              resolve(service(config))
            })
          })
        }
      }
      Message({ message: res.message, type: 'error', duration: 5000});
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  err => {
    if (err.response===undefined){
      Message({message:err.message,type: 'error',duration: 5000})
      return Promise.reject(err)
    }
    const error = err.response
    if (error.data.message===undefined){
      Message({message: error.data.error,type: 'error',duration: 5000})
      return Promise.reject(error)
    }
    Message({message: error.data.message,type: 'error',duration: 5000})
    return Promise.reject(error)
  }
)

export default service
